import * as c from '@/services/consts';
import * as api from '@/services/ticket';
import * as utils from '@/utils/utils';
import { FormOutlined, NodeExpandOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import {
  DrawerForm,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import ProList from '@ant-design/pro-list';
import type { EditableFormInstance } from '@ant-design/pro-table';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import {
  Button,
  Col,
  message,
  Popconfirm,
  Row,
  Space,
  Tag,
  Typography,
} from 'antd';
import React, { ReactText, useRef, useState } from 'react';
import { useModel } from 'umi';
const { Paragraph } = Typography;

type VpnServerFormProps = {
  visible: boolean;
  current: API.Ticket | undefined;
  onCancel: () => void;
  onSubmit: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, current, onCancel, onSubmit } = props;

  if (!visible || !current) {
    return null;
  }

  let replyCollapsed = false;

  const formRef = useRef<ProFormInstance>();
  // const [originEmailVisible, setOriginEmailVisible] = useState<boolean>(false);
  // const [supportReplyVisible, setSupportReplyVisible] = useState<boolean>(false);
  const [dataReplys, setDataReplys] = useState<API.TicketReply[] | undefined>(
    undefined,
  );
  const [dataSource, setDataSource] = useState<API.Ticket | undefined>(
    undefined,
  );
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly ReactText[]>(
    [],
  );

  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const [html, setHtml] = useState<string | undefined>('<p></p>');
  const [text, setText] = useState('');

  const editorFormRef = useRef<EditableFormInstance<API.VpnServerNet>>();
  const [type, setType] = useState(current?.status);

  const { getProductOptions, getTicketTypeTrees } = useModel(
    'useGlobalModel',
    (model) => ({
      getTicketTypeTrees: model.getTicketTypeTrees,
      getProductOptions: model.getProductOptions,
    }),
  );

  const productOptions = getProductOptions(false);

  const loadTicketTypeTreeData = async () => {
    const treeData = getTicketTypeTrees();
    if (treeData && treeData.length > 0) {
      for (let td of treeData) {
        td.children.sort((a, b) => {
          return (a.disabled ? 1 : 0) - (b.disabled ? 1 : 0);
        });
      }
    }

    return Promise.resolve(treeData);
  };

  const loadData = async () => {
    const result = await api.get({ key: current.id });
    if (result && result.success) {
      setDataSource(result.data);
      setDataReplys(result.replys);
      if (result.replys && result.replys.length > 0) {
        // setOriginEmailVisible(true);
        // setSupportReplyVisible(true);
        setExpandedRowKeys([result.replys[result.replys.length - 1].id]);
      }
    }
    return Promise.resolve(result.data);
  };

  const getTicketBaseInfo = () => {
    return {
      deviceid: formRef.current?.getFieldValue('deviceid'),
      productId: formRef.current?.getFieldValue('productId'),
      ticketType: formRef.current?.getFieldValue('ticketType'),
      appVer: formRef.current?.getFieldValue('appVer'),
      network: formRef.current?.getFieldValue('network'),
      platform: formRef.current?.getFieldValue('platform'),
      deviceModel: formRef.current?.getFieldValue('deviceModel'),
      deviceOs: formRef.current?.getFieldValue('deviceOs'),
      country: formRef.current?.getFieldValue('country'),
    };
  };

  const handleUpdateInfo = async () => {
    let data = {
      ...getTicketBaseInfo(),
      ticketId: dataSource?.id,
    };
    const result = await api.updateInfo(data);
    if (result.success) {
      message.info('更新信息成功');
    }
  };

  const handleReply = async (
    ticketId: string | undefined,
    // messageId: string | undefined,
  ) => {
    if (!ticketId) {
      message.error('问题不存在');
      return;
    }
    if (!text) {
      message.error('请输入回复内容');
      return;
    }
    let data = {
      ...getTicketBaseInfo(),
      ticketId: ticketId,
      // messageId: messageId,
      content: html,
    };
    const result = await api.reply(data);
    if (result.success) {
      onSubmit();
    }
  };

  const handleTicketClose = async () => {
    if (!text) {
      message.error('请输入关闭原因内容');
      return;
    }
    let data = {
      ...getTicketBaseInfo(),
      ticketId: dataSource?.id,
      content: html,
    };
    const result = await api.close(data);
    if (result.success) {
      onSubmit();
    }
  };

  const handleTicketFinish = async () => {
    if (!text) {
      message.error('请输入完成总结内容');
      return;
    }
    let data = {
      ...getTicketBaseInfo(),
      ticketId: dataSource?.id,
      content: html,
    };
    const result = await api.finish(data);
    if (result.success) {
      onSubmit();
    }
  };

  const handleFormSubmit = async (record: API.Ticket) => {
    onSubmit();
  };

  const toolbarConfig: Partial<IToolbarConfig> = {};
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        server: '/admin-api/ticket/img',
      },
    },
    // readOnly:true,
  };
  // editorConfig.MENU_CONF['uploadImage'] = {
  //   server: '/admin-api/ticket/img',
  // }

  return (
    <DrawerForm<API.Ticket>
      open={visible}
      // initialValues={dataSource}<Tag color='blue'>{current?.createTime}</Tag>
      title={
        <>
          用户反馈 <Tag color="blue">ID:{current.id}</Tag>{' '}
          <Tag color="error">
            {c.getObjectText(c.TicketStatusOptions, dataSource?.status)}
          </Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            //defaultDoms[0],
            // <Popconfirm
            //   key="ok"
            //   title="确定要给用户授权吗?"
            //   onConfirm={async () => {
            //     props.submit();
            //   }}
            // >
            //   <Button type="primary">确定</Button>
            // </Popconfirm>,
          ];
        },
      }}
      request={loadData}
    >
      <Row gutter={24}>
        <Col span={4}>
          <ProFormSelect
            // mode="multiple"
            name="productId"
            label="产品"
            options={productOptions}
            rules={[{ required: true, message: '请选择产品' }]}
          />
        </Col>
        <Col span={5}>
          <ProFormTreeSelect
            name="ticketType"
            label="技术支持分类"
            placeholder="请选择分类"
            allowClear={false}
            // secondary
            rules={[{ required: true, message: '请选择分类' }]}
            request={loadTicketTypeTreeData}
            // tree-select args
            fieldProps={{
              showArrow: true,
              showSearch: false,
              // treeCheckable: true,
              // multiple: true,
              treeDefaultExpandAll: true,
              listHeight: 600,
              // treeNodeLabelProp: 'title',
            }}
          />
        </Col>
        <Col span={4}>
          <ProFormText name="network" label="网络" />
        </Col>
        <Col span={4}>
          <ProFormText name="country" label="国家" />
        </Col>
        <Col span={3}>
          <ProFormDigit name="appVer" label="App版本" min={0} max={10000} />
        </Col>
        <Col span={4}>
          <Popconfirm
            key="update_info"
            title="确定要更新信息吗?"
            onConfirm={async () => {
              handleUpdateInfo();
            }}
          >
            <Button type="primary" ghost style={{ marginTop: 29 }}>
              更新信息
            </Button>
          </Popconfirm>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={4}>
          <ProFormSelect
            name="platform"
            label="设备平台"
            options={c.PlatformOptions}
          />
        </Col>
        <Col span={5}>
          <ProFormText name="deviceModel" label="设备型号" />
        </Col>
        <Col span={4}>
          <ProFormText name="deviceOs" label="设备系统" />
        </Col>
        <Col span={7}>
          <ProFormText name="deviceid" label="设备ID" />
        </Col>
        <Col span={3}></Col>
      </Row>

      <Row gutter={24}>
        <Col span={24}>
          <ProCard
            title={
              <Tag color="#2db7f5">
                <FormOutlined /> <b>问题回复</b>
              </Tag>
            }
            headStyle={{ backgroundColor: '#fafafa' }}
            bordered
            collapsible={true}
            // defaultCollapsed={supportReplyVisible}
            defaultCollapsed={true}
            headerBordered
            // onCollapse={(collapsed)=>{
            //   setSupportReplyVisible(collapsed);
            // }}
          >
            <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
              <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="simple"
                style={{ borderBottom: '1px solid #ccc' }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => {
                  setHtml(editor ? editor.getHtml() : '');
                  setText(editor ? editor.getText() : '');
                }}
                mode="simple"
                style={{
                  height: '301px',
                  overflowY: 'hidden',
                  backgroundColor: '#333',
                }}
              />
            </div>
            <div style={{ textAlign: 'right' }}>
              <Popconfirm
                key="ticket_reply"
                title="确定要提交回复吗?"
                onConfirm={async () => {
                  handleReply(dataSource?.id); //, dataSource?.originMessageId);
                }}
              >
                <Button
                  type="primary"
                  style={{ marginTop: 10, marginRight: 20 }}
                >
                  回复
                </Button>
              </Popconfirm>

              <Popconfirm
                key="ticket_close"
                title="确定要提交关闭吗?"
                style={{}}
                onConfirm={async () => {
                  handleTicketClose();
                }}
              >
                <Button
                  type="primary"
                  ghost
                  style={{ marginTop: 10, marginRight: 20 }}
                >
                  关闭
                </Button>
              </Popconfirm>

              <Popconfirm
                key="ticket_finish"
                title="确定要提交处理完结吗?"
                onConfirm={async () => {
                  handleTicketFinish();
                }}
              >
                <Button
                  type="primary"
                  ghost
                  style={{ marginTop: 10, marginRight: 20 }}
                >
                  处理完结
                </Button>
              </Popconfirm>
            </div>
          </ProCard>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={24}>
          <ProList<API.TicketReply>
            rowKey="id"
            ghost={true}
            dataSource={dataReplys}
            key="keyNotePlat"
            id="keyNotePlat"
            headerTitle={
              <>
                　用户反馈回复列表
                <a
                  onClick={async () => {
                    if (expandedRowKeys.length == dataReplys?.length) {
                      setExpandedRowKeys([]);
                    } else {
                      let keys: ReactText[] = [];
                      dataReplys?.forEach((val) => {
                        keys.push(val.id);
                      });
                      setExpandedRowKeys(keys);
                    }
                  }}
                >
                  <NodeExpandOutlined />
                </a>
              </>
            }
            metas={{
              title: {
                render: (text, record) => (
                  <div
                    onClick={() => {
                      let exRows = [...expandedRowKeys];
                      if (expandedRowKeys.indexOf(record.id) == -1) {
                        exRows.push(record.id);
                      } else {
                        exRows = exRows.filter((c) => c != record.id);
                      }
                      setExpandedRowKeys(exRows);
                    }}
                  >
                    {record.createUser ? (
                      <Tag color="#2db7f5">
                        <b>回复</b>
                      </Tag>
                    ) : (
                      <Space size={0}>
                        <Tag color="#faad14">提问</Tag>
                      </Space>
                    )}
                    <span style={{ color: '#555557', fontWeight: 'bold' }}>
                      {record.subject}
                    </span>
                    <span style={{ color: '#a8a8a9' }}>
                      　By：
                      {record.createUser
                        ? record.createUser
                        : dataSource?.contactEmail}{' '}
                      [{utils.formatUtcToLocal(record.createTime)}]
                    </span>
                  </div>
                ),
              },
              description: {
                render: (text, record) => (
                  <div>
                    <br />
                    <div
                      dangerouslySetInnerHTML={{ __html: record.content ?? '' }}
                    />
                  </div>
                ),
                fieldProps: {},
              },
            }}
            expandable={{
              expandedRowKeys,
              // expandRowByClick:true,
              defaultExpandAllRows: false,
              onExpandedRowsChange: (expandedKeys) => {
                setExpandedRowKeys(expandedKeys);
              },
            }}
          />
        </Col>
      </Row>
      {/* :""} */}
    </DrawerForm>
  );
};

export default VpnServerForm;
